<?php

require_once __DIR__.'/vendor/autoload.php';

// 加载环境变量
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

// 创建数据库连接
try {
    $pdo = new PDO(
        "mysql:host={$_ENV['DB_HOST']};dbname={$_ENV['DB_DATABASE']};charset=utf8mb4",
        $_ENV['DB_USERNAME'],
        $_ENV['DB_PASSWORD'],
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
    );

    echo "✅ 数据库连接成功\n";

    // 检查user_roles表
    $userRolesResult = $pdo->query("SELECT * FROM user_roles");
    $userRoles = $userRolesResult->fetchAll();

    echo "\n=== user_roles 表数据 ===\n";
    if (empty($userRoles)) {
        echo "❌ user_roles 表为空\n";
    } else {
        foreach ($userRoles as $ur) {
            echo "用户ID: {$ur['user_id']}, 角色ID: {$ur['role_id']}\n";
        }
    }

    // 检查用户和角色关联的详细信息
    $detailedResult = $pdo->query("
        SELECT
            u.id as user_id,
            u.username,
            u.email,
            r.id as role_id,
            r.code as role_code,
            r.name as role_name,
            ur.created_at as assigned_at
        FROM users u
        LEFT JOIN user_roles ur ON u.id = ur.user_id
        LEFT JOIN roles r ON ur.role_id = r.id
        ORDER BY u.username
    ");
    $details = $detailedResult->fetchAll();

    echo "\n=== 用户角色关联详情 ===\n";
    foreach ($details as $detail) {
        if ($detail['role_id']) {
            echo "用户: {$detail['username']} ({$detail['email']}) -> 角色: {$detail['role_name']} ({$detail['role_code']})\n";
            echo "  分配时间: {$detail['assigned_at']}\n";
        } else {
            echo "用户: {$detail['username']} ({$detail['email']}) -> 无角色分配\n";
        }
    }

} catch (Exception $e) {
    echo "❌ 错误: " . $e->getMessage() . "\n";
}
